package org.os.framework.context.config;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * webmvc配置
 * 
 * @author
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private volatile Map<String, HandlerInterceptor> interceptors;
    private volatile Map<String, HandlerMethodArgumentResolver> resolvers;

    /**
     * 注入拦截器和解析器
     * 
     * @param interceptors
     * @param resolvers
     */
    public WebMvcConfig(final Map<String, HandlerInterceptor> interceptors,
            final Map<String, HandlerMethodArgumentResolver> resolvers) {
        this.interceptors = interceptors;
        this.resolvers = resolvers;
    }

    /**
     * 注册拦截器
     */
    @SuppressWarnings("null")
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        this.interceptors.values().stream().filter(it -> it != null)
                .forEach(it -> registry.addInterceptor(it));
    }

    /**
     * 添加方法参数解析器
     */
    @SuppressWarnings("null")
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> handlerMethodArgumentResolvers) {
        List<HandlerMethodArgumentResolver> list = this.resolvers.values().stream().filter(it -> it != null)
                .collect(Collectors.toList());
        handlerMethodArgumentResolvers.addAll(list);
    }

    /**
     * 关闭SerializationFeature.FAIL_ON_EMPTY_BEANS
     */
    @SuppressWarnings("null")
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(mappingJackson2HttpMessageConverter());
    }

    private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        return new MappingJackson2HttpMessageConverter(mapper);
    }

}
